package com.fly.demo.controller;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * RestCustomerController
 * 
 * @author 00fly
 * @version [版本号, 2018-09-26]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RestController
@Api(tags = "用户操作接口")
@RequestMapping("/rest/customer")
public class RestCustomerController
{
    /**
     * 列表展示
     * 
     * @param model
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("分页查询用户")
    @GetMapping("/page")
    public String list(@RequestParam(defaultValue = "1") int pageNo)
    {
        return "ok";
    }
    
    @ApiOperation(value = "文件下载")
    @GetMapping(value = "/down", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void down(HttpServletResponse response)
        throws IOException
    {
        List<Path> filePaths = new ArrayList<>();
        Stream.of(new ClassPathResource("pic").getFile().listFiles()).forEach(lib -> filePaths.add(lib.toPath()));
        // 压缩多个文件到zip文件中
        String filename = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmss");
        response.setHeader("Content-Disposition", "attachment;filename=imgs_" + filename + ".zip");
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream()))
        {
            for (Path path : filePaths)
            {
                try (InputStream inputStream = Files.newInputStream(path))
                {
                    zipOutputStream.putNextEntry(new ZipEntry(path.getFileName().toString()));
                    StreamUtils.copy(inputStream, zipOutputStream);
                    zipOutputStream.flush();
                }
            }
        }
    }
}
